package com.baibei.ebec.user.mine;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.ebec.user.R;
import com.baibei.ebec.user.R2;
import com.baibei.model.BalanceInfo;
import com.baibei.model.InoutFundParam;
import com.baibei.model.PayModeInfo;
import com.baibei.model.UserInfo;
import com.baibei.model.event.LoginEvent;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.module.BasicFragment;
import com.baibei.module.InoutFundParamProvider;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.RxObservable;
import com.baibei.ui.AppUI;
import com.baibei.widget.dialog.PayInputPwdDialog;
import com.baibei.widget.dialog.ShareDialog;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;
import com.rae.widget.dialog.DialogBuilder;
import com.rae.widget.dialog.IAppDialog;
import com.rae.widget.dialog.IAppDialogClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.content.ContentValues.TAG;
import static com.makeramen.roundedimageview.RoundedDrawable.drawableToBitmap;

/**
 * Created by tang on 2018/11/7.
 */

public class NewMineFragment extends BasicFragment implements MineContract.View, View.OnClickListener {
    @BindView(R2.id.img_avatar)
    RoundedImageView imgAvatar;
    @BindView(R2.id.message)
    ImageView message;
    @BindView(R2.id.tv_login_tips)
    TextView tvLoginTips;
    @BindView(R2.id.tv_mobile)
    TextView tvMobile;
    @BindView(R2.id.tv_balance_title)
    TextView tvBalanceTitle;
    @BindView(R2.id.tv_balance)
    TextView mBalanceView;
    @BindView(R2.id.info_login)
    LinearLayout infoLogin;
    @BindView(R2.id.img_avatar_nologin)
    ImageView imgAvatarNologin;
    @BindView(R2.id.info_nologin)
    RelativeLayout infoNologin;
    Unbinder unbinder;
    @BindView(R2.id.btn_share)
    TextView btnShare;
    @BindView(R2.id.tv_status_certification)
    TextView mTvStatusCertification;

    private String mTag = "mine";
    private UserInfo user;
    private String userId;
    private String accessToken;
    private IUserApi mUserApi;
    private MineContract.Presenter mPresenter;
    private Dialog qrDialog;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fm_mine_new;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    public static NewMineFragment newInstance() {
        return new NewMineFragment();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);

        mUserApi = ApiFactory.getInstance().getUserApi();
        mPresenter = inject(MineContract.Presenter.class);

        if (isLogin()){
            user = SessionManager.getDefault().getUser();
            TokenInfo userToken = SessionManager.getDefault().getUserToken();
            userId = user.getUserId() + "";
            accessToken = userToken.getAccessToken();
        }

    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        updateLoginStatusView();
        if (isLogin()) {
            if (user.getUserPic() != null) {
                Glide.with(getContext()).load(user.getUserPic()).into(imgAvatar);
            }
            tvLoginTips.setText(user.getUserName());
        }
    }

    @OnClick({R2.id.img_avatar_nologin, R2.id.tv_login_tips_nologin})
    public void onNoLoginClicked(View view) {
        AppRouter.routeToLogin(getActivity());
    }

    /**
     * 更新信息
     */
    private void updateInfo() {
        if (SessionManager.getDefault().isLogin()) {
            //获取余额跟可用余额
            RxObservable.create(mUserApi.getBalanceInfo(), mTag).subscribe(new ApiDefaultObserver<BalanceInfo>() {
                @Override
                protected void onError(String s) {
                    mBalanceView.setText("余额获取失败");
                    ((BasicActivity) getActivity()).logout();
                }

                @Override
                protected void accept(BalanceInfo info) {
                    mBalanceView.setText(Rx.formatPrice(info.getBalance()));
                }
            });
            mPresenter.updateUserInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateInfo();
        updateLoginStatusView();
        if (getArguments() != null) {
            btnShare.performClick();
            setArguments(null);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!SessionManager.getDefault().isLogin()) return;
        if (isVisibleToUser) {
            if (mPresenter != null) {
                mPresenter.getIfHasNewMsg(userId, accessToken);
            }
        }
        if (isVisibleToUser && isAdded()) {
            updateInfo();
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        RxObservable.dispose(mTag);
        mPresenter.destroy();
        super.onDestroy();
    }

    @Override
    public void onCheckFundSuccess(String password, PayModeInfo info) {
        if (info == null) {
            AppUI.failed(getContext(), com.baibei.ebec.user.BuildConfig.DEBUG ? "接口没有返回提现地址数据" : "服务器正忙，请稍后重试");
            return;
        }
        //检验成功
        InoutFundParam param = InoutFundParamProvider.get();
        param.setUrl(info.getPayUrl());
        param.setFundPassword(password);
        AppRouter.routeToWithdraw(getContext(), password, param);
    }

    @Override
    public void onCheckFundFailed(String msg, boolean isLock) {
        //检验资金密码错误，弹出窗口
        DialogBuilder builder = new DialogBuilder(getContext())
                .setMessage(msg).positiveButtonText("忘记密码")
                .positiveButtonClickListener(new IAppDialogClickListener() {
                    @Override
                    public void onClick(IAppDialog iAppDialog, int i) {
                        iAppDialog.dismiss();
                        //跳转到重设资金密码
                        AppRouter.routeToResPayPwd((Activity) getContext());
                    }
                });
        //如果不是锁定，显示重新输入按钮
        if (!isLock) {
            builder.negativeButtonText("重新输入").negativeButtonClickListener(new IAppDialogClickListener() {
                @Override
                public void onClick(IAppDialog iAppDialog, int i) {
                    iAppDialog.dismiss();
                    //重新显示
                    showCheckPayDialog();
                }
            });
        }
        builder.show();
    }

    @Override
    public void onNotEnoughWithDraw(String msg) {
        AppUI.failed(getContext(), msg);
    }

    @Override
    public void showLoading() {
        AppUI.loading(getContext());
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void onUpdateUserInfo(UserInfo userInfo) {
        //是否已实名制
        if (userInfo != null && userInfo.isPassRealNameVerify()) {
            mTvStatusCertification.setText(R.string.realname_hasverify);
        } else {
            mTvStatusCertification.setText(R.string.realname_notyet);
        }

        user = SessionManager.getDefault().getUser();
        TokenInfo userToken = SessionManager.getDefault().getUserToken();
        userId = user.getUserId() + "";
        accessToken = userToken.getAccessToken();

//        LogUtils.e("log116",userInfo.getUserPic());
        Glide.with(getContext()).load(userInfo.getUserPic()).into(imgAvatar);
        tvLoginTips.setText(userInfo.getUserName());
    }

    @Override
    public void onSetMsgStatus(String status) {
        if ("0".equals(status)) {
            message.setImageResource(R.drawable.xiaoxi);
            return;
        }
        message.setImageResource(R.drawable.xiaoxihong);
    }

    /**
     * 提现操作
     * 检验资金密码
     */
    private void showCheckPayDialog() {
        PayInputPwdDialog dialog = new PayInputPwdDialog();

        dialog.setOnPayFinishListener(new PayInputPwdDialog.OnPayFinishListener() {
            @Override
            public void OnPayFinishListener(CharSequence text, DialogFragment fragment) {
                String password = text.toString();
                mPresenter.withdraw(password);
                fragment.dismiss();
            }

            @Override
            public void onDismiss() {
            }
        });
        dialog.show(getFragmentManager(), "pay");
    }

    @Subscribe
    public void onEvent(LoginEvent event) {
        updateLoginStatusView();
    }

    public void updateLoginStatusView() {
        infoLogin.setVisibility(isLogin() ? View.VISIBLE : View.GONE);
        infoNologin.setVisibility(isLogin() ? View.GONE : View.VISIBLE);
        if (isLogin()) {
            updateInfo();
        }
    }


    /**
     * 我的账单
     */
    @OnClick(R2.id.btn_bill)
    public void onBillClicked() {
        if (isLogin()) {
            AppRouter.routeToBill(getContext());
        } else {
            AppRouter.routeToLogin(getActivity());
        }
    }

    /**
     * 我的优惠券
     */
    @OnClick(R2.id.btn_ticket)
    public void onTicketClicked() {
        if (isLogin()) {
            AppRouter.routeToTicket(getContext());
        } else {
            AppRouter.routeToLogin(getActivity());
        }
    }

    /**
     * 实名认证
     */
    @OnClick(R2.id.btn_certification)
    public void onCertificationClicked() {
        if (user == null) {
            AppUI.failed(getContext(), "用户信息还没有准备好，请稍后再试。");
            return;
        }
        // 没有实名认证
        if (user.getIsRealName() == 0) {
            AppRouter.routeToNameAuth(getContext());
        } else {
            AppRouter.routeToNameAuthStatus(getContext(), null, null);
        }
    }

    /**
     * 收货地址
     */
    @OnClick(R2.id.btn_address)
    public void onAddressClicked() {
        if (isLogin()) {
            AppRouter.routeToOrderAddress(getActivity());
        } else {
            AppRouter.routeToLogin(getActivity());
        }
    }

    /**
     * 我的二维码
     */
    @OnClick(R2.id.btn_myQR)
    public void onMyQRClicked() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
            return;
        }
        qrDialog = new Dialog(getContext());
        Window window = qrDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        qrDialog.setContentView(R.layout.dialog_qr);
        ImageView ivClose = qrDialog.findViewById(R.id.iv_close);
        ImageView ivQR = qrDialog.findViewById(R.id.iv_QR);

        UserInfo userInfo = SessionManager.getDefault().getUser();
        int userId = userInfo.getUserId();
        String shareUrl = BuildConfig.API_BASE_URL + "ddtj/index.html?invitationCode=" + userId +
                "&exchange=CB_GUOXIANG&memberChannel=999";
//        ivQR.setImageBitmap(QRCode.createQRCode(shareUrl));
        ivQR.setImageBitmap(QRCode.createQRCodeWithLogo6(shareUrl, 500, drawableToBitmap(getResources().getDrawable(R.drawable.ic_logo))));

        ivClose.setOnClickListener(this);

        qrDialog.setCanceledOnTouchOutside(false);
        qrDialog.show();
    }

    /**
     * 分享APP
     */
    @OnClick(R2.id.btn_share)
    public void onShareClicked() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
        } else {
            ShareDialog dialog = new ShareDialog(getContext());
            // http://cbecfat.100bei.com/cbclient/index.html?invitationCode=
//            dialog.setShareWeb("http://cbecfat.100bei.com/cbclient/index.html?invitationCode=" + mUserInfo.getInvitationCode(), getString(R.string.share_title), getString(R.string.share_content), null);
            //分享监听，是否安装微信
            dialog.setOnShareClickListener(new ShareDialog.OnShareClickListener() {
                @Override
                public void onShare(Dialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onShareFailed(Dialog dialog, String msg) {
                    dialog.dismiss();
                    AppUI.failed(getContext(), msg);
                }
            });
            TokenInfo userToken = SessionManager.getDefault().getUserToken();
            String token = userToken.getAccessToken();
            UserInfo userInfo = SessionManager.getDefault().getUser();
            int userId = userInfo.getUserId();
//            String url = String.format(BuildConfig.API_BASE_URL + "cbclient/index.html?accessToken=" + token,
//                    mUserInfo.getInvitationCode(), BuildConfig.EXCHANGE, ApiConstant.MEMBER_CHANNEL);

            String url = BuildConfig.API_BASE_URL + "ddtj/index.html?invitationCode=" + userId +
                    "&exchange=CB_GUOXIANG&memberChannel=999";
            dialog.setShareWeb(url, getString(R.string.share_title), getString(R.string.share_content), null);
            int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());
            dialog.setInvitationCode(user.getInvitationCode());
            dialog.show();
        }
    }

    /**
     * 帮助中心
     */
    @OnClick(R2.id.btn_help)
    public void onHelpClicked() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
        } else {
            AppRouter.routeToSetting(this.getContext());
        }
    }

    /**
     * 设置
     */
    @OnClick(R2.id.btn_setting)
    public void onSettingClicked() {
        if (!isLogin()) {
            AppRouter.routeToLogin(getActivity());
        } else {
            AppRouter.routeToSetting(this.getContext());
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_close) {
            qrDialog.dismiss();
        }
    }

    @OnClick({R2.id.img_avatar, R2.id.tv_login_tips, R2.id.tv_mobile})
    public void onViewClicked(View view) {
        startActivity(new Intent(getActivity(), UserInfoActivity.class));
    }
}
